class CommunitiesController < ApplicationController
	before_filter :find_community, :only=>[:show, :destroy, :edit, :update, :join]
  before_filter :login_required, :except=>[:show, :index]
    
  def index
    @communities = Community.paginate(:page => params[:page], :per_page => 15, :order=>"created_at DESC")
  end
  
  def new
  	@community = Community.new
  end
  
  def create
  	Community.transaction do
    	#@community = Community.create!(params[:community])
    	#@community.create_logo(params[:logo]) unless params[:logo][:uploaded_data].blank?
    	#current_user.memberships.create(:community=>@community, :role_id=>Role.detect(Role::ADMIN))
			@community = Community.new(params[:community])
    	@community.user = current_user
			if @community.save!
				unless params[:logo].blank?
    			@community.logo.create(params[:logo]) unless params[:logo][:uploaded_data].blank?
    		end
    		current_user.memberships.create(:community=>@community, :role_id=>Role.detect(Role::ADMIN))
    	end
    end
    redirect
    rescue ActiveRecord::RecordInvalid
    	render :action => 'new'
  end
    
  def update
    @community.update_attributes!(params[:community])
    
    if params[:logo] && !params[:logo][:uploaded_data].blank?
    	@community.logo.nil? ? @community.create_logo(params[:logo]) : @community.logo.update_attributes(params[:logo])
    end
    redirect
    rescue ActiveRecord::RecordInvalid
    	render :action => 'edit'
  end
  
  def destroy
    @community.destroy
    redirect
  end
  
  def join
    if params[:act] == "1" 
  		current_user.memberships.create(:community=>@community, :role_id=>Role.detect(Role::DEFAULT))
    else
    	memb = current_user.memberships.find_by_community_id(@community.id)
    	memb.destroy if memb
    end
  	redirect
  end
  
  private
  
  def authorized?
  	return logged_in? if ['show', 'new', 'create', 'join'].include?(action_name)
    logged_in? && (current_user.admin? || current_user == @community.user)
  end
  
  def find_community
    @community = Community.find(params[:id])
  end
  
  def redirect
		redirect_to communities_path
  end
end
